# -*- coding: UTF-8 -*-

# Copyright (c) 2007 Daniele Favara <nomed@dsslive.org>.
#
# This is free software you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# This software is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software; see the file COPYING.  If not, write to the Free
# Software Foundation, Inc., 51 Franilin St, Fifth Floor, Boston, MA


from configobj import ConfigObj
import sqlalchemy



class Loader(object):
    import sys
    import os
    import logging
    import turbogears as tg
    import tginvoice
    from tginvoice.utils import support
    from tginvoice.utils import option
    from tginvoice.utils import misc
    from tginvoice.utils import standard



    import validate
    if sys.version_info < (2, 3):
        sys.exit("error: Python 2.3 or later required")

    def _get_tables(self):
        from tginvoice.model import tables
        return tables

    tables = property(_get_tables)

    def _get_insert(self):
        from tginvoice.model import insert
        return insert

    insert = property(_get_insert)

    def select(self):
        from tginvoice.model import select
        return select

    def __init__(self, config):
        self._set_logger()
        self.OptionParser = self.option.OptionParser
        self.APPNAME = self.tginvoice.__name__
        self.COMMANDS = {}
        self.CLASSES = {}

        self.home = self.os.path.abspath(
                        self.os.path.join(
                            self.os.path.realpath(self.os.path.dirname(__file__)),
                            '../'))
        self._config = config

        #if self.config.has_key('SYSPATH'):
        #    for key, value in self.config['SYSPATH'].iteritems():
        #        self.sys.path.insert(0, value)
        for md_name in ['commands','classes']:
            for md in self.support.get_modules(self.tginvoice.__file__,
                    md_name):
                dct = getattr(self, md_name.upper())
                modulename = '.'.join([self.tginvoice.__name__,md_name])
                name = md.replace('_','-')
                if self.support.is_importable(modulename, name):
                    dct[name]=self.support.import_name(modulename, name)
                else:
                    print "ERROR:", md

    def _get_metadata(self):
        return self.tables.metadata
    metadata = property(_get_metadata)

    def _get_session(self):
        return self.tables.session
    session = property(_get_session)

    def _get_config(self):
        return self._config
    config = property(_get_config)

    def _get_date(self):
        import datetime
        TIMESTAMP = datetime.datetime.now()
        STRFTIME = "%d/%m/%Y %H:%M"
        date = TIMESTAMP.strftime(STRFTIME)
        return date
    date = property(_get_date)

    def _set_logger(self):
        logger = self.logging.getLogger('APP')
        logger.setLevel(self.logging.DEBUG)
        logger_handler = self.logging.StreamHandler()
        logger_formatter = self.logging.Formatter(
        #'%(asctime)s %(name)-8s %(levelname)-8s %(message)s'
        '%(name)-8s %(levelname)-8s %(message)s'
        )
        logger_handler.setFormatter(logger_formatter)
        logger.addHandler(logger_handler)
        self.logger = logger

#    def _set_engine(self):
#        """Retrieve the engine based on the current configuration."""
#        if not hasattr(self,'engine'):
#            self.engine = self.tables.engine
#            self._set_connection()
#            alch_args = dict()
#            alch_args['echo'] = self.config.get('sqlalchemy.echo')
#            dburi = self.config.get('sqlalchemy.dburi')
#            if not dburi:
#                raise KeyError("No sqlalchemy database config found!")
#            engine = sqlalchemy.create_engine(dburi, **alch_args)
#            if not self.metadata.is_bound():
#                self.metadata.bind = engine
#            setattr(self, 'engine', engine)
#            self._set_connection()
#
#            return True
#        return False

#    def _set_connection(self):
#        self.session = self.tables.session
#        self.connection = self.tables.connection
#        from sqlalchemy.orm import sessionmaker, scoped_session
#        Session = scoped_session(sessionmaker(bind=self.engine, autoflush=True, transactional=True))
#        self.session = Session
#
#        self.connection = self.engine.connect()

    def set(self, name, value):
        setattr(self, name, value)

    def fubar(self, msg, exit_code=1):
        self.sys.stderr.write("E: %s\n" % (msg))
        self.sys.exit(exit_code)

    def log_function(self, function, action, *args,**kw):
        self.logger.debug("* %s %s %s"%(function,action, args))
        if kw:
               self.logger.debug("\t%s"%(kw))
#    def our_raw_input(self,prompt=""):
#        import sys
#        if prompt:
#            sys.stdout.write(prompt)
#        sys.stdout.flush()
#        try:
#            ret = raw_input()
#            return ret
#        except EOFError:
#            sys.stderr.write("\nUser interrupt (^D).\n")
#            raise SystemExit